﻿let currentpath = "";
let currentfile = "";
let selectfoler = false;
let selectfile = false;
let isModified = false;
let interval = 0;
let emailglobal = ""
let delcloudfile = ""
let downloadselect = "0"
let downloadfolder = ""

const tooltipTriggerList = document.querySelectorAll('[data-tooltip="tooltip"]')
const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))

//textarea支持tab缩进
$("textarea").on(
    'keydown',
    function (e) {
        if (e.keyCode == 9) {
            e.preventDefault();
            var indent = '    ';
            var start = this.selectionStart;
            var end = this.selectionEnd;
            var selected = window.getSelection().toString();
            selected = indent + selected.replace(/\n/g, '\n' + indent);
            this.value = this.value.substring(0, start) + selected
                + this.value.substring(end);
            this.setSelectionRange(start + indent.length, start
                + selected.length);
        }
    })

$(document).ready(function () {
    bindTreeEvents();
});

function handleTextareaChange() {
    if (!isModified) {
        isModified = true;
        $('#saveStatus').text('未保存');
    }
    let input = $("#textMsg").val();
    $("#output").html(csf.converttohtml(input));
    $("#charCount").html(input.length);
}

function openFolder() {
    $("#fileitem").html(csf.openfolder());
    bindTreeEvents(); // 重新绑定事件处理器
}

function openFile(name) {
    $("#textMsg").val(csf.openfile(name));
    handleTextareaChange();
}

function bindTreeEvents() {
    $('.caret').off('click').on('click', function () {
        $(this).parent().find('.nested').first().toggleClass('active');
        $(this).toggleClass('caret-down');
        $('.caret').css('background-color', 'white');
        $('.file-item').css('background-color', 'white');
        $(this).css('background-color', '#bebebe');
        currentpath = $(this).attr("name");
        $('#newfilepath').html(currentpath);
        $('#newfolderpath').html(currentpath);
        selectfoler = true;
        selectfile = false;
    });

    $('.file-item').off('click').on('click', function () {
        $('.caret').css('background-color', 'white');
        $('.file-item').css('background-color', 'white');
        $(this).css('background-color', '#bebebe');
        currentfile = $(this).attr("name");
        selectfoler = false;
        selectfile = true;
    });
}

function createfile() {
    $("#fileitem").empty();
    let newfileitem = csf.newfile(currentpath, $('#newfilename').val());
    $('#newfilename').val('');
    $("#fileitem").html(newfileitem);
    bindTreeEvents();
    $('#newfile').modal('hide');
    currentpath = csf.retprojectfolder();
    $('#newfilepath').html(currentpath);
    $('#newfolderpath').html(currentpath);
}

function createfolder() {
    $("#fileitem").empty();
    let newfolderitem = csf.newfolder(currentpath, $('#newfoldername').val());
    $('#newfoldername').val('');
    $("#fileitem").html(newfolderitem);
    bindTreeEvents();
    $('#newfolder').modal('hide');
}

function freshTree() {
    $("#fileitem").empty();
    $("#fileitem").html(csf.generatefiletree());
    bindTreeEvents();
    $('#toastText').html('刷新成功!')
    const toastLive = $('#liveToast')
    const toast = new bootstrap.Toast(toastLive)
    toast.show()
}

$(document).keydown(function (event) {
    if (event.ctrlKey && event.key === 's') {
        event.preventDefault();
        saveFileContent();
    }
});

function saveFileContent() {
    let content = $("#textMsg").val();
    if(currentfile === "" || !selectfile)
        return;
    csf.savefile(currentfile, content);
    isModified = false;
    $('#saveStatus').text('已保存');
    $('#toastText').html("保存成功！")
    const toastLive = $('#liveToast')
    const toast = new bootstrap.Toast(toastLive)
    toast.show()
}

function deleteItem() {
    if (!currentpath && !currentfile) {
        alert("请选择要删除的文件或文件夹。");
        return;
    }
    let updatedTree = "";
    if (selectfile) {
        updatedTree = csf.deletefile(currentfile);
    } else if (selectfoler) {
        updatedTree = csf.deleteFolder(currentpath);
    }
    $("#fileitem").empty();
    $("#fileitem").html(updatedTree);
    bindTreeEvents();
    $('#confirmDelete').modal('hide');
    $('#toastText').html('删除成功!')
    const toastLive = $('#liveToast')
    const toast = new bootstrap.Toast(toastLive)
    toast.show()
}

$('#VerCodeGet').click(async function () {
    let email = $('#RegEmail').val().trim();
    let button = $(this);

    if (email === "") {
        alert("请先填写邮箱地址。");
        return;
    }

    let countdown = 59;
    button.prop('disabled', true); // 将按钮设为不可用
    interval = setInterval(function () {
        button.text(countdown + ' 秒');
        countdown--;
        if (countdown < 0) {
            clearInterval(interval);
            button.text('获取验证码');
            button.prop('disabled', false); // 恢复按钮可用
        }
    }, 1000);

    try {
        let response = await csfa.getverificationcode(email);
        console.log(response); // 可以在这里处理服务器返回的验证码
        if (response === "402") {
            $('#RegEmail').css('border-color', 'red');
            $('#emailExist').show();
            setInterval(function () {
                $('#RegEmail').css('border-color', '');
            }, 1000);
            throw new Error('402');
        }
    } catch (error) {
        console.error("Error getting verification code:", error);
        clearInterval(interval);
        button.text('获取验证码');
        button.prop('disabled', false); // 恢复按钮可用
    }
});

$('#Reg').on('hidden.bs.modal', function () {
    clearInterval(interval);
    let button = $('#VerCodeGet');
    button.text('获取验证码');
    button.prop('disabled', false); // 恢复按钮可用
});

$('#RegPassAgain').on('input', function () {
    let password = $('#RegPass').val();
    let confirmPassword = $(this).val();

    if (password !== confirmPassword) {
        $('#RegPassAgain').css('border-color', 'red');
        $('#passwordMismatch').show();
    } else {
        $('#RegPassAgain').css('border-color', '');
        $('#passwordMismatch').hide();
    }
});

// 注册处理函数
$('#regisbutton').click(async function () {
    let email = $("#RegEmail").val().trim();
    let password = $("#RegPass").val();
    let confirmPassword = $("#RegPassAgain").val();
    let code = $("#VerCode").val()
    let button = $(this);

    if (password !== confirmPassword)
        return;

    button.prop('disabled', true); // 将按钮设为不可用
    button.text("请稍后...");

    try {
        let response = await csfa.newuser(email, password, code);
        console.log(response); // 可以在这里处理服务器返回的验证码
        if (response === "401") {
            $('#VerCode').css('border-color', 'red');
            $('#VerCodeErr').show();
            setInterval(function () {
                $('#VerCode').css('border-color', '');
            }, 1000);
        } else {
            $('#Reg').modal('hide');
            $('#tab3').html(
                "<h5>欢迎使用MDnote!</h5>\n" +
                "<p>亲爱的" + email + "</p>\n" +
                "<div class=\"d-grid gap-3\">\n" +
                "<button type=\"button\" class=\"btn btn-secondary btn-lg mx-auto\" data-bs-toggle=\"pill\" data-bs-target=\"#tab2\"  role=\"tab\" style=\"width: 95%; margin-right: 5px\">查看云文档</button>\n" +
                "<button type=\"button\" class=\"btn btn-secondary btn-lg mx-auto\" id=\"exitlogin\" style=\"width: 95%; margin-right: 5px\">退出登录</button>\n" +
                "</div>"
            )
            bindButtonEvents(); // 新增这行代码
            $("#RegEmail").val('')
            $("#RegPass").val('')
            $("#RegPassAgain").val('')
            $("#VerCode").val('')
            emailglobal = email
            $('#toastText').html("亲爱的" + email + ',欢迎使用MDnote!')
            const toastLive = $('#liveToast')
            const toast = new bootstrap.Toast(toastLive)
            toast.show()
        }
    } catch (error) {
        console.error("Error getting verification code:", error);
    } finally {
        button.text("注册");
        button.prop('disabled', false); // 恢复按钮可用
    }
});

// 登录处理函数
$('#signup').click(async function () {
    let email = $("#floatingEmail").val().trim();
    let password = $("#floatingPassword").val();
    let button = $(this);

    button.prop('disabled', true); // 将按钮设为不可用
    button.text("请稍后...");

    try {
        let response = await csfa.loginmd(email, password);
        if (response === "402") {
            $('#floatingEmail').css('border-color', 'red');
            $('#floatingEmailErr').show();
            setInterval(function () {
                $('#floatingEmail').css('border-color', '');
            }, 1000);
        } else if (response === "404") {
            $('#floatingPassword').css('border-color', 'red');
            $('#floatingPasswordErr').show();
            setInterval(function () {
                $('#floatingPassword').css('border-color', '');
            }, 1000);
        } else {
            $('#login').modal('hide');
            $('#tab3').html(
                "<h5>欢迎使用MDnote!</h5>\n" +
                "<p>亲爱的" + email + "</p>\n" +
                "<div class=\"d-grid gap-3\">\n" +
                "<button type=\"button\" class=\"btn btn-secondary btn-lg mx-auto\" data-bs-toggle=\"pill\" data-bs-target=\"#tab2\" style=\"width: 95%; margin-right: 5px\">查看云文档</button>\n" +
                "<button type=\"button\" class=\"btn btn-secondary btn-lg mx-auto\" id=\"exitlogin\" style=\"width: 95%; margin-right: 5px\">退出登录</button>\n" +
                "</div>"
            )
            bindButtonEvents();
            $("#floatingEmail").val('')
            $("#floatingPassword").val('')
            $('#cloudfileitem').html(response)
            emailglobal = email
            $('#toastText').html("亲爱的" + email + ',欢迎使用MDnote!')
            const toastLive = $('#liveToast')
            const toast = new bootstrap.Toast(toastLive)
            toast.show()
        }
    } catch (error) {
        console.error("Error getting verification code:", error);
    } finally {
        button.text("登录");
        button.prop('disabled', false); // 恢复按钮可用
    }
});

function bindButtonEvents() {
    $('#exitlogin').off('click').on('click', function () {
        $('#tab3').html(
            "<strong style=\"font-size: x-large\">您尚未登录...</strong>\n" +
            "<div class=\"d-grid gap-3\">\n" +
            "<button type=\"button\" class=\"btn btn-secondary btn-lg mx-auto\" data-bs-toggle=\"modal\" data-bs-target=\"#Reg\" style=\"width: 95%; margin-right: 5px\">注册</button>\n" +
            "<button type=\"button\" class=\"btn btn-secondary btn-lg mx-auto\" data-bs-toggle=\"modal\" data-bs-target=\"#login\" style=\"width: 95%; margin-right: 5px\">登录</button>\n" +
            "</div>"
        );
        emailglobal = ""
        $('#cloudfileitem').html('')
    });

    $('button[data-bs-target="#tab2"]').off('click').on('click', function () {
        var tab2 = new bootstrap.Tab(document.getElementById('tab2-tab'));
        tab2.show();
    });
}

$('#uploadbutton').click(async function () {
    let button = $(this);
    button.prop('disabled', true); // 将按钮设为不可用
    button.text("上传中...");

    let response = await csfa.uploadfile(emailglobal, currentfile, $('#uploadfilemane').val())

    button.prop('disabled', false); // 将按钮设为不可用
    button.text("上传");
    $('#uploadfile').modal('hide')
    $('#cloudfileitem').html(response)
    $('#toastText').html("上传成功！")
    const toastLive = $('#liveToast')
    const toast = new bootstrap.Toast(toastLive)
    toast.show()
})

function uploadfile() {
    if (!selectfile) {
        alert("当前未选择文件!");
        return;
    }
    if (emailglobal === "") {
        alert("您尚未登录!")
        return;
    }
    $('#uploadfilemane').val(currentfile.substring(currentfile.lastIndexOf('\\') + 1, currentfile.length))
    $('#uploadfile').modal('show')
}

function deletecloudfile(name) {
    delcloudfile = name
    $('#confirmDeleteCloud').modal('show')
}

$('#confirmDeleteCloudButton').click(async function () {
    let button = $(this);
    button.prop('disabled', true); // 将按钮设为不可用
    button.text("正在处理...");

    let response = await csfa.deletecloudfile(emailglobal, delcloudfile)
    $('#cloudfileitem').html(response)

    button.prop('disabled', false); // 将按钮设为可用
    button.text("删除");
    $('#confirmDeleteCloud').modal('hide')
    $('#toastText').html("删除成功!")
    const toastLive = $('#liveToast')
    const toast = new bootstrap.Toast(toastLive)
    toast.show()
})

async function downloadfile(name) {
    if(downloadselect === '1' && currentpath === ""){
        alert("当前未选中文件夹！")
        return
    }
    await csfa.downloadfile(emailglobal, name, downloadselect,currentpath, downloadfolder)
    
    $('#toastText').html("下载完成！")
    const toastLive = $('#liveToast')
    const toast = new bootstrap.Toast(toastLive)
    toast.show()
}

$('#fontSize').on('input', updateStyles);
$('#lineHeight').on('input', updateStyles);
function updateStyles() {
    const fontSize = ($('#fontSize').val() || '16') + 'px';
    const lineHeight = $('#lineHeight').val() || 'normal';

    $('#textMsg').css('fontSize', fontSize);
    $('#textMsg').css('lineHeight', lineHeight);

    $('#output').css('fontSize', fontSize);
    $('#output').css('lineHeight', lineHeight);
}

$('#downloadPlace').on('change', function() {
    downloadselect = $(this).val()
    if ($(this).val() === '2') {
        downloadfolder = csf.selectdownloadfolder();
        $('#downloadFolder').html(downloadfolder);
    }
});